package com.wuseguang.springcloud.mina;


import org.apache.mina.core.service.IoAcceptor;
import org.apache.mina.core.service.IoHandler;
import org.apache.mina.core.session.IdleStatus;
import org.apache.mina.filter.codec.ProtocolCodecFilter;
import org.apache.mina.filter.logging.LoggingFilter;
import org.apache.mina.transport.socket.nio.NioSocketAcceptor;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;

import java.net.InetSocketAddress;
import java.util.ArrayList;
import java.util.List;

@Configuration
public class MinaConfig {



    /** 15秒发送一次心跳包 */
    private static final int HEARTBEATRATE = 15;

    @Bean
    public LoggingFilter loggingFilter() {
        return new LoggingFilter();
    }

    @Bean
    public IoHandler ioHandler8004() { return new Server8004Handler(); }

    @Bean
    public IoHandler ioHandler53600() { return new Server53600Handler(); }

    @Bean
    public InetSocketAddress inetSocketAddress8004() {
        return new InetSocketAddress(8004);
    }

    @Bean
    public InetSocketAddress inetSocketAddress53600() {
        return new InetSocketAddress(53600);
    }

    @Bean
    public List<IoAcceptor> ioAcceptor() throws Exception {

        List<IoAcceptor> list = new ArrayList<IoAcceptor>();

        IoAcceptor acceptor8004 = new NioSocketAcceptor();
        acceptor8004.setHandler(ioHandler8004()); //自定义处理业务的代码：自定义的类
        acceptor8004.bind(inetSocketAddress8004());//绑定端口号
        acceptor8004.getFilterChain().addLast("logger", loggingFilter());
        acceptor8004.getFilterChain().addLast("mycoder", new ProtocolCodecFilter(new ByteArrayCodecFactory()));

        /*acceptor.getFilterChain().addLast("coderc",   // 使用自定义编码解码工厂类
                new ProtocolCodecFilter(new TextLineCodecFactory(Charset.forName("UTF-8"))));//设置编码过滤器*/

        acceptor8004.getSessionConfig().setReadBufferSize(1024*1024);//设置缓冲区
        acceptor8004.getSessionConfig().setIdleTime(IdleStatus.BOTH_IDLE, 10);  //配置会话信息

        IoAcceptor acceptor53600 = new NioSocketAcceptor();
        acceptor53600.setHandler(ioHandler53600()); //自定义处理业务的代码：自定义的类
        acceptor53600.bind(inetSocketAddress53600());//绑定端口号
        acceptor53600.getFilterChain().addLast("logger", loggingFilter());
        acceptor53600.getFilterChain().addLast("mycoder",  new ProtocolCodecFilter(new ByteModleCodecFactory()));

       /* acceptor53600.getFilterChain().addLast("coderc",   // 使用自定义编码解码工厂类
                new ProtocolCodecFilter());//设置编码过滤器*/

        acceptor53600.getSessionConfig().setReadBufferSize(1024*1024);//设置缓冲区
        acceptor53600.getSessionConfig().setIdleTime(IdleStatus.BOTH_IDLE, 10);  //配置会话信息

        System.err.println("Socket服务器在端口已经启动");


        list.add(acceptor8004);
        list.add(acceptor53600);
        return list;
    }






}
